//
//  BaseViewController.m
//  CreditHub
//
//  Created by xinhualong on 2024/9/12.
//

#import "BaseViewController.h"
#import "CHLocationManager.h"
#import "HomeRequest.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

@interface BaseViewController ()<UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate >

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.orderNo = @"";
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [self addNavView];
    
}
- (void)addNavView{
    self.ch_navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SYS_TopHeight)];
    self.ch_navigationView.layer.zPosition = CGFLOAT_MAX;
    [self.view addSubview: self.ch_navigationView];
    
    self.navBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SYS_TopHeight)];
    self.navBgImageView.image = [UIImage imageNamed:@"home_dakawei_header"];
    self.navBgImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.navBgImageView.hidden = YES;
    self.navBgImageView.clipsToBounds = YES;
    [self.ch_navigationView addSubview:self.navBgImageView];
    
    
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    [self.ch_navigationView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(SYS_StatusBarHeight);
        make.height.offset(44);
        make.centerX.mas_equalTo(0);
    }];
    

    self.titleImageView = [[UIImageView alloc] init];
    [self.ch_navigationView addSubview:self.titleImageView];
    [self.titleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.titleLabel.mas_left).offset(-10);
        make.centerY.equalTo(self.titleLabel.mas_centerY);
        make.height.width.offset(24);
    }];
    
    self.backButton = [[UIButton alloc] init];
    [self.backButton setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [self.ch_navigationView addSubview:self.backButton];
    [self.backButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(SYS_StatusBarHeight);
        make.height.offset(44);
    }];
    if(self.navigationController.viewControllers.count <=1){
        self.backButton.hidden = YES;
    }
    
}
- (void)setCh_titleImage:(UIImage *)ch_titleImage{
    _ch_titleImage = ch_titleImage;
    self.titleImageView.image = ch_titleImage;
}
-(void)setCh_title:(NSString *)ch_title{
    _ch_title = ch_title;
    self.titleLabel.text = ch_title;
}

- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

- (void)openCameraOrGalleryType:(NSString*)type;{
    
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"Take a picture" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectImage:UIImagePickerControllerSourceTypeCamera type:type];
    }];
    

    UIAlertAction *chooseFromLibraryAction = [UIAlertAction actionWithTitle:@"Photo album" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectImage:UIImagePickerControllerSourceTypePhotoLibrary type:type];
    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];

    [alertController addAction:takePhotoAction];
    [alertController addAction:chooseFromLibraryAction];
    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)selectImage:(UIImagePickerControllerSourceType)sourceType type:(NSString *)type{
    
    self.cardType = type;
    if(sourceType == UIImagePickerControllerSourceTypeCamera){
        self.sourceType = 1;
    }else{
        self.sourceType = 2;
    }
    
    [self checkCameraAndPhotoLibrarySourceType:sourceType];
    
 
    
//    self.block = block;

}

#pragma mark - UIImagePickerControllerDelegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        if ([weakSelf.delegate respondsToSelector:@selector(selectedFinishTaskWithResultImage:sourceType:type:)]) {
                [weakSelf.delegate selectedFinishTaskWithResultImage:chosenImage sourceType:weakSelf.sourceType type:weakSelf.cardType];
            }
//        weakSelf.block(chosenImage,weakSelf.sourceType);
    }];
}
- (void)checkCameraAndPhotoLibrarySourceType:(UIImagePickerControllerSourceType)sourceType  {
    
    if(sourceType == UIImagePickerControllerSourceTypeCamera){
        AVAuthorizationStatus cameraStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (cameraStatus) {
            case AVAuthorizationStatusAuthorized:{
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.allowsEditing = NO;
                picker.sourceType = sourceType;
                if([self.cardType isEqualToString:@"10"]){
                    picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
                }
                
                [self presentViewController:picker animated:YES completion:nil];
            }
               
                break;
            case AVAuthorizationStatusDenied:
            case AVAuthorizationStatusRestricted:
               
                [self showPermissionAlert];
                break;
            case AVAuthorizationStatusNotDetermined:{
                
            }
                //unknown
                __weak typeof(self) weakSelf = self;
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (granted) {
                            
                            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                            picker.delegate = self;
                            picker.allowsEditing = NO;
                            picker.sourceType = sourceType;
                            if([weakSelf.cardType isEqualToString:@"10"]){
                                picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
                            }
                            [weakSelf presentViewController:picker animated:YES completion:nil];
                            
                        } else {
                            
                            [weakSelf showPermissionAlert];
                        }
                    });
                }];
                break;
        }
    }else{
        // PhotoLibrary
        PHAuthorizationStatus photoLibraryStatus = [PHPhotoLibrary authorizationStatus];
        switch (photoLibraryStatus) {
            case PHAuthorizationStatusAuthorized:
            case PHAuthorizationStatusLimited:{
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.allowsEditing = NO;
                picker.sourceType = sourceType;
                [self presentViewController:picker animated:YES completion:nil];
            }
               
                break;
            case PHAuthorizationStatusDenied:
            case PHAuthorizationStatusRestricted:
               
                [self showPermissionAlert];
                break;
            case PHAuthorizationStatusNotDetermined:{
                
            }
              //unknown
                __weak typeof(self) weakSelf = self;
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (status == PHAuthorizationStatusAuthorized) {
                            
                            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                            picker.delegate = self;
                            picker.allowsEditing = NO;
                            picker.sourceType = sourceType;
                            [weakSelf presentViewController:picker animated:YES completion:nil];
                            
                        } else {
                            
                            [weakSelf showPermissionAlert];
                        }
                    });
                }];
                break;
        }
    }
}
- (void)showPermissionAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Permission not enabled" message:@"In order to use this application function normally, please go to the Settings to enable permissions" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:@"Go to Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:goToSettingsAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark ---- public upload

- (void)everyTimeUpdateHomeInfo{
    
    [self uploadLocation];
    [self uploadGoogleInfo];
    [self uploadDeviceInfo];
}

- (void)uploadLocation{
    [[CHLocationManager sharedInstance] startUpdatingLocation];
}
- (void)uploadGoogleInfo{
    
    [HomeRequest requestUploadGoogleMarketSuccess:^(NSURLSessionDataTask *task, id response) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
- (void)uploadDeviceInfo{
    
    [HomeRequest requestUploadDeviceSuccess:^(NSURLSessionDataTask *task, id response) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
- (void)requestUploadPointType{
    
    [HomeRequest requestUploadPointType:CHString(self.pointType) orderNo:CHString(self.orderNo) startTime:CHString(self.startTime) endTime:CHString(self.endTime) success:^(NSURLSessionDataTask *task, id response) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
